package com.gable.controller;

import com.gable.util.MD5Util;
import com.gable.util.ReturnResultUtil;
import com.gable.dao.RoleDao;
import com.gable.model.Url;
import com.gable.model.User;
import com.gable.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 登录
 * @author Aioria
 *
 */
@Controller
public class LoginController {
	
	private final Log logger = LogFactory.getLog(this.getClass());

	@Resource
	HttpServletRequest request;
	
	@Resource
	HttpServletResponse response;
	
	@Autowired
	UserService userService;

	@Autowired
	RoleDao iRoleDao;

	@Value("${hospitalType}")
	String hospitalType;


	@Value("${loginAddress}")
	String loginAddress;
	
	/**
	 * 进入登录页面
	 * @return
	 */
	@RequestMapping(value="/login-error",method=RequestMethod.GET)
	public String toLogin(){
		return "login";
	}
	/**
	 * 进入首页面
	 * @return
	 */
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String toIndex(){
		return "index";
	}

	/**
	 * 功能说明：用户登陆模块
	 * @throws IOException 
	 * @return,
	 */
		@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(String username,String password,RedirectAttributes attr) throws IOException{
		// 接受返回值Map
		ReturnResultUtil rru = userService.login(username, MD5Util.md5(password));	//MD5Util.md5()给密码加密
		// 取出登陆状态
		// 1表示登陆成功，如果登陆成功就向session放参数
		if(rru.getRet() == 200){
			User user = (User)rru.getData();
			HttpSession session=request.getSession();
			session.setAttribute("loginUser", user);
			List<Url> auth =  iRoleDao.roleAuth(user.getRoleId()).get(0).getUrlList();
			session.setAttribute("auth",auth);
			session.setAttribute("longName", user.getName());
			session.setAttribute("longRole", user.getRole());
			session.setAttribute("phone", user.getPhone());
			session.setAttribute("loginAddress",loginAddress);
			return "redirect:/index";
		}
			request.getSession().setAttribute("msg",rru.getMsg());

		return "redirect:/login-error";
	}

	/**
	 * 功能说明：退出登陆注销session
	 * 创建人：乔春峰
	 * 创建时间：2016年9月13日 19:51:27
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="logout",method=RequestMethod.GET)
	public String logout() throws IOException{
		HttpSession session=request.getSession();	
		session.invalidate();
		return "redirect:/";
	}
	
	@RequestMapping(value="/authorityOut")
	public String authorityOut(){
		return "authority500";
	}


	/**
	 * 判断该用户是否需要强制修改密码
	 * @param lastLoginTime
	 * @return
	 */
	public boolean lastLoginTime(String lastLoginTime){
		if(lastLoginTime == null){
			return false;
		}

		Date date = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		long day = getDistanceDays(lastLoginTime,df.format(date));
		if(day > 90){
			return true;
		}
		return false;
	}


	public static long getDistanceDays(String str1, String str2){
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date one;
		Date two;
		long days=0;
		try {
			one = df.parse(str1);
			two = df.parse(str2);
			long time1 = one.getTime();
			long time2 = two.getTime();
			long diff ;
			if(time1<time2) {
				diff = time2 - time1;
			} else {
				diff = time1 - time2;
			}
			days = diff / (1000 * 60 * 60 * 24);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return days;
	}
}
